package model;

import java.awt.Dimension;
import java.awt.Rectangle;
import java.util.HashMap;

import model.element.ElementFactory;
import model.element.Road;
import control.Ticker;

public class World extends Ticker<Element> implements Ticking{
	private HashMap<Dimension, Road> roadMap = new HashMap<Dimension, Road>(); 
	
	
	@Override
	public synchronized boolean add(Element added){
		if(added.isBlocking()){
			for(Element e : this){
				if(e.isBlocking()&&added.getRectangle().intersects(e.getRectangle())){
					return false;
				}
			}
			for(Element e : toAdd){
				if(e.isBlocking()&&added.getRectangle().intersects(e.getRectangle())){
					return false;
				}
			}
		}
		return toAdd.add(added);
	}
	

	public synchronized void addRoad(Road r){
		roadMap.put(new Dimension(r.getX(), r.getY()), r);
	}
	
	public synchronized boolean blocked(Element e){
		for(Element element : this){
			if(element.blocks(e)){
				return true;
			}
		}
		return false;
	}
	
	public Road getRoad(Dimension d){
		return roadMap.get(d);
	}
	
	public Road getRoad(int x, int y){
		return roadMap.get(new Dimension(x,y));
	}
	
	/* returns the Road object underneath this Element */ 
	public Road getRoadUnderneath(Element e){
		int x = e.getX();
		int y = e.getY();
		Road r = this.getRoad(x - (x % Road.ROAD_SIZE), y - (y % Road.ROAD_SIZE));
		return r;
	}
}
